import { ref, reactive, type Ref, shallowRef, onMounted } from "vue";

import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type {
  ActionItem,
  ActionFormItemProps as _ActionFormItemProps
} from "./type/eventActionTypes";
import { h } from "vue";
import eventActionForm from "../componentsForm/eventActionForm.vue";

export function useEventActionTable(
  tableRef: Ref,
  lesseeId: number,
  dealerId: number
) {
  const form = reactive({
    eventId: 0,
    actionName: "",
    SearchTerm: "",
    OrderBy: ""
  });
  const formRef = shallowRef();
  const dataList = ref<ActionItem[]>([]);
  const loading = ref(false);
  const selectedNum = ref(0);
  const eventOptions = ref<Array<{ value: number; label: string }>>([]);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 列表列定义
  const columns = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    //{ label: "ID", prop: "Id", width: 80 },
    { label: "事件ID", prop: "EventId", width: 80 },
    { label: "事件名称", prop: "EventName", minWidth: 120 },
    { label: "段", prop: "Section", width: 80 },
    { label: "动作", prop: "Action", minWidth: 150 },
    { label: "动作参数", prop: "ActionParams", minWidth: 150 },
    { label: "创建时间", prop: "CreateTime", minWidth: 150 },
    { label: "操作", fixed: "right", width: 150, slot: "operation" }
  ];

  // 设备检测函数（适配移动端）
  function deviceDetection() {
    return window.innerWidth < 768;
  }

  // 获取事件列表用于下拉选择
  function getEventOptions() {
    http
      .get(changeHttpLink("/api/Event"), {
        params: {
          tenantId: lesseeId
        }
      })
      .then((res: any) => {
        if (res.Success) {
          // 将获取的用户列表转换为下拉列表选项
          eventOptions.value = res.Data.Items.map((item: any) => ({
            label: item.Name,
            value: item.Id
          }));
          eventOptions.value.unshift({
            label: "默认事件",
            value: 0
          });
          //console.log("事件列表数据:", eventOptions.value);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }

  // 获取、搜索执行动作列表
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      PageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      keyword: form.SearchTerm,
      eventId: form.eventId,
      tenantId: lesseeId
    };
    console.log(params);
    http
      .get(changeHttpLink("/api/EventAction"), {
        params
      })
      .then((res: any) => {
        if (res.Success) {
          dataList.value = res.Data || [];
          pagination.total = res.Data.TotalCount || 0;
          console.log(dataList.value);
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  // 重置表单
  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 新增、修改执行动作
  function openDialog(title: string, row: any = null) {
    const id = row?.Id ?? "";
    // 确保先获取事件选项
    addDialog({
      title: `${title}执行动作`,
      props: {
        formInline: {
          Id: row?.Id ?? 0,
          dealerId: dealerId,
          tenantId: lesseeId,
          eventId: row?.EventId ?? 0,
          section: row?.Section ?? 0,
          action: row?.Action ?? "",
          actionParams: row?.ActionParams ?? ""
        },
        title: title,
        eventOptions: eventOptions.value
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(eventActionForm, {
          ref: formRef,
          formInline: null,
          title: title,
          eventOptions: eventOptions.value
        }),

      beforeSure: (done, { options: _options }) => {
        const FormRef = formRef.value.getRef();
        const curData = formRef.value.getFormData();
        function chores() {
          message(
            `您${title}了执行动作ID为【${curData.id || "新创建"}】的这条数据`,
            {
              type: "success"
            }
          );
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              ...curData,
              tenantId: lesseeId,
              dealerId: dealerId
            };
            console.log(formData);
            if (title === "创建") {
              http
                .post(changeHttpLink("/api/EventAction"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else {
              http
                .request("put", changeHttpLink(`/api/EventAction/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            }
          }
        });
      }
    });
  }

  // 删除执行动作
  function handleDelete(row: ActionItem) {
    ElMessageBox.confirm(
      `是否确认删除执行动作ID为${row.Id}的这条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .request("delete", changeHttpLink(`/api/EventAction/${row.Id}`), {
            data: row.Id
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`您删除了执行动作ID为${row.Id}的这条数据`, {
                type: "success"
              });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.Id);

    ElMessageBox.confirm(
      `是否确认删除选中的${listIds.length}条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .request("delete", changeHttpLink("/api/EventAction/batch"), {
            data: { ids: listIds }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除选中的${listIds.length}条数据`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 分页相关
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 选择相关
  function handleSelectionChange(val: any[]) {
    selectedNum.value = val.length;
  }

  function onSelectionCancel() {
    tableRef.value.getTableRef().clearSelection();
  }
  // 添加初始化调用
  onMounted(() => {
    getEventOptions();
    onSearch();
  });
  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    eventOptions,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    getEventOptions
  };
}
